<template>
  <div>
    <v-autocomplete>
      :v-model="select" :items="autoItems" :loading="loading"
      :search-input.sync="search" item-text="text" item-value="value"
      :disable-lookup="false" multiple chips clearable deletable-chips dense
    </v-autocomplete>
  </div>
</template>

export default {
    name:"MaterialAutoComplete",

    props: {
      items: {
        type: Array,
        default: () => ([])
      },
    }
    // 略过其它属性
    data() {
        return {
            autoItems: [],
            loading: false,
            currentSearchValue: '',
            search: null,
            select: null
        }
    },
    watch: {
        select(val) {
            // 触发changeVal事件，更改select到的item的value
            this.$emit('changeVal', val)
        },
        search(val) {
            this.currentValue = val
            // 注意保持缓存的items，不要加清空items的逻辑，否则先前传出去的item的value（select）也没了
            this.handleSearch(val)
        },
        items(newValues){
            this.autoItems = newValues;
        }
    },
    methods: {
        handleSearch(v) {
            var _this = this
            setTimeout(() => {
                if (!_this.currentValue === v) {
                    return
                }
                _this.loading = true
                // 下面是自定义的检索items的逻辑
                asyncSearch().then((resp) => {
                    if (resp.code === 200 && _this.currentValue === v) {
                        _this.items = resp.data.map(d => ({
                            ...d,
                            text: d.textPart,  // 显示的文本
                            value: d.valuePart,  // 真正要传出去的值
                        }))
                    }
                    _this.loading = false
                }).catch(() => {
                    _this.loading = false
                })
            }, 200)
        }
    }
}

